﻿package com.agileai.miscdp.hotweb.ui.editors.treemanage;

import java.io.File;
import java.io.StringWriter;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;

import com.agileai.miscdp.hotweb.domain.BaseFuncModel;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.treemanage.TreeManageFuncModel;
import com.agileai.miscdp.hotweb.ui.editors.BaseModelEditor;
import com.agileai.miscdp.hotweb.ui.views.TreeObject;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.hotweb.model.EditTableType;
import com.agileai.hotweb.model.treemanage.TreeManageFuncModelDocument;
import com.agileai.util.FileUtil;
import com.agileai.util.StringUtil;
/**
 * 单表操作功能模型编辑器
 */
public class TreeManageModelEditor extends BaseModelEditor{
	private TMMBasicConfigPage basicConfigPage;
	private TMMJspCfgPage jspCfgPage;
	
    public void init(IEditorSite site, IEditorInput input) throws PartInitException {
        setSite(site);
        setInput(input);
        setPartName(input.getName());
		init();
		ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
    }
	private void init() {
		funcModel = (TreeManageFuncModel)this.getEditorInput();
	}

	protected void createPages() {
		basicConfigPage = new TMMBasicConfigPage(getContainer(),this,SWT.NONE);
		jspCfgPage = new TMMJspCfgPage(getContainer(),this,SWT.NONE);
		setFuncModel((TreeManageFuncModel)funcModel);
		
		String basicConfig = MiscdpUtil.getIniReader().getValue("EditorInfo","BasicInfo");
		int basicConfigIndex = addPage(basicConfigPage);
		setPageText(basicConfigIndex,basicConfig);
		basicConfigPage.createContent();
		
		String detailJspConfig = MiscdpUtil.getIniReader().getValue("EditorInfo","DetailInfo");
		int detailJspCfgIndex = addPage(jspCfgPage);
		setPageText(detailJspCfgIndex, detailJspConfig);
		jspCfgPage.createContent();
		
		initValues();
		
		basicConfigPage.registryModifier();
		jspCfgPage.registryModifier();
	}
	public void doSave(IProgressMonitor monitor) {
		try {
			TreeManageFuncModel suFuncModel = buildFuncModel();

	    	String projectName = suFuncModel.getProjectName();
	    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
	    	
	    	String listJspName = basicConfigPage.getExtendAttributes().getJspNameText().getText();
	    	if (StringUtil.isNullOrEmpty(listJspName)){
	    		String listJspCheckNullMsg = MiscdpUtil.getIniReader().getValue("TreeManageModelEditor","ListJspCheckNullMsg");
	    		DialogUtil.showInfoMessage(listJspCheckNullMsg);
	    		return;
	    	}
	    	
	    	String abstSqlMapPath = project.getLocation().toString()+"/src/sqlmap";
	    	File tempFile = new File(abstSqlMapPath);
	    	if (!tempFile.exists()){
	    		tempFile.mkdirs();
	    	}
//	    	String sqlMapFileName = MiscdpUtil.getValidName(tableName); 
//	    	String sqlMapFile = abstSqlMapPath + "/" + sqlMapFileName+".xml";

	    	TreeManageFuncModelDocument funcModelDocument = (TreeManageFuncModelDocument)buildFuncModelDocument(suFuncModel);
			StringWriter writer = new StringWriter();
			funcModelDocument.save(writer);
			String funcName = suFuncModel.getFuncName();
			String funcSubPkg = suFuncModel.getFuncSubPkg();
			
			String funcDefine = writer.toString();
			String funcId = suFuncModel.getFuncId();
			String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
			FileUtil.writeFile(fileName, funcDefine);
			
			this.isModified = false;
			firePropertyChange(PROP_DIRTY);
			
			TreeViewer funcTreeViewer = funcModelTree.getFuncTreeViewer();
			ISelection selection = funcTreeViewer.getSelection();
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			TreeObject treeObject = null;
			if (obj instanceof TreeObject) {
				treeObject = (TreeObject) obj;
				treeObject.setName(funcName);
				treeObject.setFuncSubPkg(funcSubPkg);
			}

			updateIndexFile(projectName);
			
			this.setPartName(funcName);
			funcTreeViewer.refresh();
			try {
				suFuncModel.buildFuncModel(funcDefine);
				project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public TMMBasicConfigPage getBasicConfigPage() {
		return basicConfigPage;
	}
	public TMMJspCfgPage getJspCfgPage() {
		return jspCfgPage;
	}
	public void setFuncModel(TreeManageFuncModel funcModel) {

	}
	public TreeManageFuncModel buildFuncModel() {
		return this.basicConfigPage.buildConfig();
	}
	public void initValues() {
		this.basicConfigPage.initValues();
		this.jspCfgPage.initValues();
	}
	public TreeManageFuncModel getFuncModel() {
		return (TreeManageFuncModel)funcModel;
	}
	public Object buildFuncModelDocument(BaseFuncModel baseFuncModel){
		TreeManageFuncModel treeManageFuncModel = (TreeManageFuncModel)baseFuncModel;
		TreeManageFuncModelDocument funcModelDocument = TreeManageFuncModelDocument.Factory.newInstance();
		TreeManageFuncModelDocument.TreeManageFuncModel funcModel = funcModelDocument.addNewTreeManageFuncModel();
		TreeManageFuncModelDocument.TreeManageFuncModel.BaseInfo baseInfo = funcModel.addNewBaseInfo();
		String tableName = treeManageFuncModel.getTableName();
		baseInfo.setPageTitle(treeManageFuncModel.getPageTitle());
		baseInfo.setTemplate(treeManageFuncModel.getTemplate());
		baseInfo.setJspName(treeManageFuncModel.getJspName());
		baseInfo.setTableName(tableName);
		baseInfo.setPkGenPolicy(treeManageFuncModel.getPkGenPolicy());
		
		baseInfo.setIdField(treeManageFuncModel.getIdField());
		baseInfo.setNameField(treeManageFuncModel.getNameField());
		baseInfo.setParentIdField(treeManageFuncModel.getParentIdField());
		baseInfo.setSortField(treeManageFuncModel.getSortField());
		
		TreeManageFuncModelDocument.TreeManageFuncModel.BaseInfo.Service service = baseInfo.addNewService();
		String interfaceName = treeManageFuncModel.getInterfaceName();
		service.setServiceId(treeManageFuncModel.getServiceId());
		service.setImplClassName(treeManageFuncModel.getImplClassName());
		service.setInterfaceName(interfaceName);
		
		String jspName = treeManageFuncModel.getJspName();
		String editHandlerId = jspName.substring(0,jspName.length()-4);
		editHandlerId = editHandlerId.substring(editHandlerId.lastIndexOf("/")+1,editHandlerId.length());
		String tempClassPath = interfaceName.substring(0,interfaceName.lastIndexOf(".")).replace("bizmoduler","controller"); 
		String editHandlerClass = tempClassPath + "." + editHandlerId + "Handler";
		TreeManageFuncModelDocument.TreeManageFuncModel.BaseInfo.Handler handler = baseInfo.addNewHandler();
		handler.setHandlerId(editHandlerId);
		handler.setHandlerClass(editHandlerClass);
		
		TreeManageFuncModelDocument.TreeManageFuncModel.BaseInfo.SqlResource sqlResource = baseInfo.addNewSqlResource();
		sqlResource.setSqlNameSpace(tableName.toLowerCase());
		String sqlMapPath = "sqlmap/"+tableName+".xml";;
		sqlResource.setSqlMapPath(sqlMapPath);
		
		TreeManageFuncModelDocument.TreeManageFuncModel.PageView pageView = funcModel.addNewPageView();
		EditTableType currentEditTableType = pageView.addNewCurrentEditArea();
		List<PageFormField> pageFormFields = treeManageFuncModel.getPageFormFields();
		this.processEditTableType(treeManageFuncModel,pageFormFields, currentEditTableType,false,"");
		
		EditTableType childEditTableType = pageView.addNewChildCreateArea();
		this.processEditTableType(treeManageFuncModel,pageFormFields, childEditTableType, true, "CHILD_");
		return funcModelDocument;
	}
}
